<!DOCTYPE html>
<html>
  <head>
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, user-scalable=no"
    />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>百度静态地图展示</title>
    <style type="text/css">
      html,
      body {
        height: 100%;
        margin: 0;
        padding: 0;
        overflow: hidden;
      }
      #map-container {
        position: relative;
        width: 100%;
        height: 100%;
      }
      #static-map {
        width: 100%;
        height: 100%;
        object-fit: cover;
        display: none;
      }
      .loading {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-family: Arial, sans-serif;
        color: #666;
      }
      .error {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        color: red;
        display: none;
      }
    </style>
    <!-- 引入百度地图API -->
    <script src="https://api.map.baidu.com/api?v=3.0&ak=TnnvUz71nq8nInn6dsFjdKHQeQzMO7u2"></script>
  </head>
  <body>
    <div id="map-container">
      <div class="loading">地图加载中...</div>
      <div class="error" id="error-msg"></div>
      <img id="static-map" alt="百度静态地图" />
    </div>

    <script type="text/javascript">
      // 配置参数
      const config = {
        ak: 'TnnvUz71nq8nInn6dsFjdKHQeQzMO7u2', // 百度AK
        defaultCenter: '118.66146545960594,32.0958783989593', // 默认中心点
        zoom: 15, // 默认缩放级别
        debug: false, // 是否开启调试模式
        markerStyle: 'color:blue|label:S|116.404,39.915', // 标记样式
      }

      // 全局变量
      let currentLocation = null
      let messagePort = null
      let isMapLoaded = false
      let convertedCenter = null // 存储转换后的中心点

      // 初始化函数
      function init() {
        setupMessageListener()
        // 初始加载默认地图
        loadStaticMap()
      }

      // 坐标转换（WGS84 -> BD09）并加载地图
      function convertAndLoadMap(longitude, latitude) {
        // 创建百度地图转换器实例
        const convertor = new BMap.Convertor()

        // 转换坐标
        convertor.translate(
          [new BMap.Point(longitude, latitude)],
          1, // 源坐标类型：1(WGS84)
          5, // 目标坐标类型：5(BD09MC)
          (result) => {
            if (
              result.status === 0 &&
              result.points &&
              result.points.length > 0
            ) {
              const convertedPoint = result.points[0]
              convertedCenter = `${convertedPoint.lng},${convertedPoint.lat}`

              // 使用转换后的坐标加载地图
              loadStaticMap(convertedCenter)
            }
          }
        )
      }

      // 加载静态地图
      function loadStaticMap(center = config.defaultCenter) {
        const mapImg = document.getElementById('static-map')
        const loadingElement = document.querySelector('.loading')
        const errorElement = document.getElementById('error-msg')

        // 显示加载状态
        loadingElement.style.display = 'block'
        errorElement.style.display = 'none'
        mapImg.style.display = 'none'

        // 构建地图URL
        const mapUrl =
          `https://api.map.baidu.com/staticimage/v2?` +
          `ak=${config.ak}&` +
          `center=${center}&` +
          `width=${window.innerWidth}&` +
          `height=${window.innerHeight}&` +
          `zoom=${config.zoom}&` +
          `markers=${center}&` +
          `markerStyles=${encodeURIComponent(config.markerStyle)}`

        // 设置图片源并处理加载事件
        mapImg.onload = function () {
          loadingElement.style.display = 'none'
          mapImg.style.display = 'block'
          isMapLoaded = true

          if (config.debug) {
            console.log('地图加载成功:', center)
          }
        }

        mapImg.onerror = function () {
          loadingElement.style.display = 'none'
          errorElement.textContent = '地图加载失败，请刷新重试'
          errorElement.style.display = 'block'

          if (config.debug) {
            console.error('地图加载失败:', center)
          }
        }

        mapImg.src = mapUrl
        mapImg.alt = `百度静态地图 - 中心点: ${center}`
      }

      // 设置消息监听
      function setupMessageListener() {
        window.addEventListener('message', function (event) {
          // 初始化端口通信
          if (
            event.data === '__init_port__' &&
            event.ports &&
            event.ports.length > 0
          ) {
            messagePort = event.ports[0]
            messagePort.onmessage = handlePortMessage
            return
          }

          // 直接消息处理
          handleAppMessage(event.data)
        })
      }

      // 处理端口消息
      function handlePortMessage(event) {
        handleAppMessage(event.data)
      }

      // 处理应用消息
      function handleAppMessage(data) {
        let locationData = null

        // 解析消息数据
        if (typeof data === 'string') {
          locationData = JSON.parse(data)
        } else if (typeof data === 'object') {
          locationData = data
        }

        // 验证位置数据
        if (locationData && locationData.longitude && locationData.latitude) {
          currentLocation = locationData
          // 转换坐标并更新地图
          convertAndLoadMap(locationData.longitude, locationData.latitude)
        }
      }

      // 页面加载完成后初始化
      window.onload = init
    </script>
  </body>
</html>
